package com.example.h5shell.http;

import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class OkHttpService {

    // 全局OkHttpClient实例
    private static OkHttpClient client = new OkHttpClient();

    // 发送GET请求
    public static void get(String url, Callback callback) {
        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(callback);
    }

    // 发送POST请求（表单数据）
    public static void postForm(String url, String formBody, Callback callback) {
        FormBody.Builder formBuilder = new FormBody.Builder();
        String[] keyValues = formBody.split("&");
        for (String keyValue : keyValues) {
            String[] keyValueSplit = keyValue.split("=");
            if (keyValueSplit.length == 2) {
                formBuilder.add(keyValueSplit[0], keyValueSplit[1]);
            }
        }

        RequestBody requestBody = formBuilder.build();
        Request request = new Request.Builder().url(url).post(requestBody).build();

        client.newCall(request).enqueue(callback);
    }

    // 发送POST请求（JSON数据）
    public static void postJson(String url, String json, Callback callback) {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(json, JSON);

        Request request = new Request.Builder().url(url).post(requestBody).build();

        client.newCall(request).enqueue(callback);
    }

}
